package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.dto.BedDto;
import com.zzyl.entity.Bed;
import com.zzyl.entity.Room;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.BedMapper;
import com.zzyl.mapper.RoomMapper;
import com.zzyl.mapper.RoomTypeMapper;
import com.zzyl.service.BedService;
import com.zzyl.vo.BedVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BedServiceImpl implements BedService {

    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private RoomTypeMapper roomTypeMapper;

    @Override
    public List<BedVo> getBedsByRoomId(Long roomId) {
        return bedMapper.getBedsByRoomId(roomId);
    }

    @Override
    public void addBed(BedDto bedDto) {
//todo bed_number需要做重复校验
        Bed bed = BeanUtil.toBean(bedDto, Bed.class);
        bed.setCreateTime(LocalDateTime.now());
        bed.setBedStatus(0);
        bed.setCreateBy(1L);
        Long count=  bedMapper.repeatBedNumber(bed.getBedNumber());
        if (count>0){
            throw new BaseException(BasicEnum.BED_INSERT_FAIL_REPEAT_BED_NUMBER);
        }
        bedMapper.addBed(bed);
        //根据roomID查询床位对应的房间信息
        Room room = roomMapper.selectById(bedDto.getRoomId());
        if (room!=null){
            roomTypeMapper.incrBedCountByRoomTypeName(room.getTypeName());
        }
        //只有床位编号不重复才能新增

    }

    @Override
    public void updateBed(BedDto bedDto) {
        BedVo bedVo = selectById(bedDto.getId());
        bedVo.setSort(bedDto.getSort());
        bedVo.setBedNumber(bedDto.getBedNumber());
        Bed bed = BeanUtil.toBean(bedVo, Bed.class);
        bed.setUpdateTime(LocalDateTime.now());
        //如果bedNumber重复则无法修改bedNumber
        Long count=  bedMapper.countDiffBedNumber(bed.getBedNumber(),bed.getId());
        if (count>0){
            throw new BaseException(BasicEnum.BED_INSERT_FAIL_REPEAT_BED_NUMBER);
        }
        //如果状态不为0，在空闲中无法修改
        Long statusId=  bedMapper.getStatusByBed(bed.getId());
        if (statusId!=0){
            throw new BaseException(BasicEnum.BED_INSERT_FAIL);
        }
        bedMapper.updateBed(bed);


    }

    @Override
    public BedVo selectById(Long id ) {
     BedVo vo=  bedMapper.selectById(id);
     return vo;
    }

    @Override
    public void deleteById(Long id) {
        bedMapper.deleteById(id);
    }


}

